﻿#region Copyright
// Partial Copyright (c) LogoUI Software Solutions LTD
// Author: Vladislav Spivak
// This source file is the part of LogoFX Framework http://logofx.codeplex.com
// See accompanying licences and credits.
#endregion


using System;
using System.Collections;
using System.Windows.Input;
using System.Linq;
#if !WinRT
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Interactivity;
using LogoFX.Core;
using EventTrigger = System.Windows.Interactivity.EventTrigger;


namespace LogoFX.Infra.Interactivity
{
    /// <summary>
    /// Provides selection change on key input
    /// </summary>
    public class JumpToValueBehavior
        : Behavior<Selector>
    {

        public string JumpToPropertyName { get; set; }
        public bool IsJumpToValueCaseSensitive { get; set; }


        protected override void OnAttached()
        {
            base.OnAttached();

            this.AssociatedObject.TextInput += new TextCompositionEventHandler(AssociatedObject_TextInput);
        }

        void AssociatedObject_TextInput(object sender, TextCompositionEventArgs e)
        {
            //ToDo collect keystrokes and combine them to allow for multiple letters
            if (!string.IsNullOrEmpty(this.JumpToPropertyName))
            {
                string keyValue = e.Text;

                if (!string.IsNullOrEmpty(keyValue))
                {

                    var items = from object i in this.AssociatedObject.Items
                                where i != null && CompareJumpToValue(i.GetType()
                                    .GetProperty(this.JumpToPropertyName)
                                    .GetValue(i, null).ToString(), keyValue)
                                select i;

                    object firstItem = items.FirstOrDefault();

                    if (firstItem != null)
                    {
                        this.AssociatedObject.SelectedItem = firstItem;
                    }


                }

                e.Handled = true;
            }
        }

        protected override void OnDetaching()
        {
            base.OnDetaching();

            this.AssociatedObject.TextInput -= AssociatedObject_TextInput;

        }

        protected bool CompareJumpToValue(string itemValue, string textInput)
        {

            bool result = false;

            if (this.IsJumpToValueCaseSensitive)
            {
                result = itemValue.StartsWith(textInput, StringComparison.InvariantCulture);
            }
            else
            {
                result = itemValue.StartsWith(textInput, StringComparison.OrdinalIgnoreCase);
            }


            return result;
        }
    }
}
#endif